from datetime import timedelta, datetime

from django.http import JsonResponse
from django.shortcuts import render
from django.db import connection
from django.utils import timezone
from ebisu import ebisu
from pytz import UTC

from dict.models import Word, RecallRecord


def index_view(request):
    if request.method == 'POST':
        grade = request.POST['grade']
        qs = Word.objects.all()
        if qs.count() == 0:
            qs = Word.objects.all()
        data = []
        if qs.count() > 0:
            data = [{
                'id': q.id,
                '单词': q.text,
                '发音': q.phonetic,
                '意思': q.meaning,
                '年级': q.grade,
                '技巧': q.trick,
            } for q in qs]
        return JsonResponse(data, safe=False)
    return render(request, 'dict/index.html')


# 更新单词
def update_word(request):
    result = {'status': False, 'err': ''}
    try:
        post = request.POST
        trick = post['技巧']
        id_word = int(post['id'])
        word = Word.objects.get(pk=id_word)
        if trick == '' and word.trick is not None:
            trick = word.trick
        # word.update(grade=post['年级'], trick=trick)
        word.grade = post['年级']
        word.trick = trick
        word.save()
        result['status'] = True
    except Exception as e:
        print(e)
        result['err'] = str(e)
    return JsonResponse(result)


# 回忆
def recall_view(request):
    if RecallRecord.objects.all().count() == 0:
        with connection.cursor() as cursor:
            sql = '''insert into dict_recallrecord (word_id, successes, total, alpha, beta, t, recall, last_test, last_cal) 
            select id, 0, 1, 3.0, 3.0, 24.0, 0, current_timestamp, current_timestamp from dict_word'''
            cursor.execute(sql)
    # 取recall<50
    data = []
    qs = RecallRecord.objects.filter(recall__lt=50)
    if qs.count() > 0:
        data = [{
            'id': q.id,
            '单词': q.word.text,
            '发音': q.word.phonetic,
            '意思': q.word.meaning,
            '技巧': '' if q.word.trick is None else q.word.trick,
        } for q in qs]
    return render(request, 'dict/recall.html', {'data': data})


# 更新单词状态
def update_word_status(request):
    result = {'status': False, 'err': ''}
    try:
        post = request.POST
        id_word = int(post['id'])
        success = post['success']

        # 更新记录，α、β、t
        obj = RecallRecord.objects.get(id=int(id_word))
        obj.total += 1  # 记总数
        if success == 'success':
            obj.successes += 1  # 记成功数
        obj.recall = 100
        model = (obj.alpha, obj.beta, obj.t)
        one = timedelta(hours=1)
        model_new = ebisu.updateRecall(model, obj.successes, obj.total,
                                       (datetime.now(timezone.utc) - obj.last_test) / one)
        obj.alpha = round(model_new[0], 2)
        obj.beta = round(model_new[1], 2)
        obj.t = round(model_new[2], 2)
        obj.save()

        result['status'] = True
    except Exception as e:
        print(e)
        result['err'] = str(e)
    return JsonResponse(result)
